<!--医院端--新建订单--批发采购订单-->
<template>
  <div class="newPurchaseList-box">
    <el-container class="newPurchase-box">
      <!-- 头部 -->
      <h3 class="title">基础信息</h3>
      <el-header
        height="auto"
        class="form-wrapper">
        <el-form
          :model="purchaseOrderInfo"
          :rules="rules"
          ref="purchaseOrderForm"
          label-width="130px"
          class="demo-ruleForm"
          :inline="true"
        >
          <el-form-item
            label="申请科室"
            prop="applyDept">
            <el-select
              v-model="purchaseOrderInfo.applyDept"
              filterable
              placeholder="请输入关键词"
              remote
              clearable
              :remote-method="remoteMethod"
              @focus="getDeptList"
            >
              <el-option
                v-for="item in applyDeptList"
                :key="item.id"
                :label="item.departName"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item
            label="收货地址"
            prop="storageAddress">
            <el-select
              v-model="purchaseOrderInfo.storageAddress"
              :loading="addressLoading"
              placeholder="请选择"
              @change="changeAddress(purchaseOrderInfo.storageAddress)"
            >
              <el-option
                v-for="(item, index) in addressList"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="联系人"
            prop="userName">
            <el-input
              v-model="purchaseOrderInfo.userName"
              disabled/>
          </el-form-item>
          <el-form-item
            label="联系电话"
            prop="userPhone">
            <el-input
              v-model="purchaseOrderInfo.userPhone"
              disabled=""/>
          </el-form-item>
        </el-form>
      </el-header>
      <!-- 列表模块 -->
      <h3 class="title">采购产品</h3>
      <div
        class="top-add-button-wrapper"
        v-if="!isEmptyList">
        <div class="title-info">
          <span>已选择产品数量 : {{ computedCount }}</span>
          <span>品种数 :{{ computedType }}</span>
          <span class="order-total-amount">金额合计(元):
            <span style="color:red;">
              {{ formatPrice(orderTotalAmount()) }}
            </span>
          </span>
        </div>
        <span class="add-button">
          <el-button
            type="primary"
            @click="openAddProductDialog"
            size="small">添加产品</el-button>
          <el-button
            type="button"
            @click="batchDelete"
            size="small">批量删除</el-button>
        </span>
      </div>
      <el-editable
        v-if="!isEmptyList"
        v-loading="tableLoading"
        :data="curPageList"
        height="400"
        :columns="purchaseOrderProductListColumns"
        @selection-change="handleSelectionChange"
      >
        <!-- 规格型号 -->
        <template
          slot="default-specification"
          slot-scope="scope">
          <div>{{ scope.row.spec }} {{ scope.row.model }}</div>
        </template>
        <template
          slot="default-registNo"
          slot-scope="scope">
          <div>
            <cell-registration
              :key="scope.row.registNo"
              :regis-no="scope.row.registNo"
              :content="'注册证已过期，点击查看详细信息'"
              :status="scope.row.expireStatus"
              :regis-data="scope.row.registInfo"
            />
          </div>
        </template>
        <template
          slot="default-purchaseNum"
          slot-scope="scope">
          <el-input-number
            v-model="scope.row.count"
            @change="resetIllegalInput(scope,$event)"
            size="mini"
            :step="1"
            :min="1"
            :max="9999999"
            label="描述文字"
            step-strictly
            on-keypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
          />
        </template>
        <template
          slot="default-action"
          slot-scope="scope">
          <el-button
            size="small"
            @click.stop="deleteOrderProductItem(scope)"
            type="text text-danger"
          >删除</el-button>
        </template>
      </el-editable>
      <!-- 分页模块 -->
      <div
        class="center-add-button-wrapper"
        v-if="isEmptyList">
        <el-button
          type="primary"
          @click="openAddProductDialog">+ 添加产品</el-button>
      </div>
      <!-- 选择采购产品 -->
      <add-product-dialog
        :dialog-visible.sync="addProductDialogShow"
        title="选择采购产品"
        :query-url="hospitalHosCooperationProdList"
        query-method="post"
        :extra-query="sCompanyQuery"
        :current-products="purchaseOrderProductList"
        @confirmDialog="addSelectionToProductList"
        @cancelDialog="cancelAddSelection"
        :type='dialogType'
      />
    </el-container>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { purchaseOrderProductListColumns } from './const'
import SearchForm from '@components/businesscomponents/search'
import ElEditable from '@components/el-editable'
import CellRegistration from '@/moduleComponents/common/detail/cell-registration'
import AddProductDialog from '@/moduleComponents/beforeSettle/hospitalSide/addProduct'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import { computeRate, computeAdd } from '@const/filter'
import {
  createPurchaseOrder,
  editPurchaseOrder
} from '@const/orderCenterApi'
import { organizationUcSearchCurr } from '@const/staffCenterApi'
import { partnerList } from '@const/authCenterApi'
import { hospitalHosCooperationProdList } from '@const/productCenterApiV2'
import { formatPrice } from '@const/agencySaas'
import { cloneDeep, isObject, uniqBy, hasIn } from 'lodash'
import {
  getAddressListAll,
  getHospitalPurchaseOrderItem,
  hospitalwscPurchaseOrderCreate
} from '@const/beforeSettleApi'

export default {
  components: { ElEditable, SearchForm, AddProductDialog, CellRegistration },
  data () {
    return {
      hospitalHosCooperationProdList,
      purchaseOrderProductListColumns, // 页面产品列表表头
      addProductDialogShow: false,
      addressList: [],
      addressLoading: false,
      purchaseOrderInfo: {
        storageAddress: '',
        userPhone: '',
        userName: '',
        applyDept: ''
      },
      computedCount: 0,
      purchaseOrderProductList: [],
      purchaseOrderProductTableList: [],
      rules: {
        storageAddress: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        applyDept: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      tableLoading: false, // 这里的loading只有在扩展编辑订单功能之后才有用
      selectList: [],
      applyDeptList: [],
      computedType: 0,
      dialogType: 'hospital'
    }
  },
  watch: {
    curPageList: {
      immediate: true,
      handler (val) {
        let sumCount = 0
        this.curPageList.forEach(item => {
          sumCount += item.count
        })
        this.computedCount = sumCount
        this.computedType = this.curPageList.length
      }
    }
  },
  computed: {
    ...mapState(['companyId', 'companyType', 'roleType']),
    isEmptyList () {
      return this.purchaseOrderProductList.length === 0
    },

    curPageList () {
      return this.purchaseOrderProductTableList
    },
    sCompanyQuery () {
      return {
        // dealerId: this.companyId,
        dealerId: this.purchaseOrderInfo.sCompanyId
      }
    }
  },

  mounted () {
    let obj = {
      type: 'btn',
      arr: [{ type: 'primary', val: '提交', handle: this.handleSubmit }]
    }
    this.$store.commit('changeLayoutHandle', obj)
    // 查询收货地址
    this.getAddressList()
  },
  methods: {
    formatPrice,
    // 合并行
    // arraySpanMethod ({ row, column, rowIndex, columnIndex }) {},
    // 批量删除
    batchDelete () {
      this.purchaseOrderProductList.forEach(item => {
        this.selectList.forEach(ite => {
          if (item.dealerAuthItemId === ite.dealerAuthItemId) {
            this.purchaseOrderProductList = this.purchaseOrderProductList.filter(
              it => {
                return it.dealerAuthItemId !== item.dealerAuthItemId
              }
            )
            this.selectList = this.selectList.filter(it => {
              return it.dealerAuthItemId !== item.dealerAuthItemId
            })
            this.ProductList()
          }
        })
      })
    },
    // 远程搜索科室名称
    remoteMethod (query) {
      this.$axios({
        method: 'post',
        url: organizationUcSearchCurr,
        data: {
          departName: query
        }
      }).then(res => {
        let obj = hasIn(res, 'data.payload') ? res.data.payload : {}
        this.applyDeptList = obj.content
      })
    },
    // 申请科室第一次获取鼠标焦点时触发
    getDeptList () {
      this.$axios({
        method: 'post',
        url: organizationUcSearchCurr,
        data: {
          departName: ``
        }
      }).then(res => {
        let obj = hasIn(res, 'data.payload') ? res.data.payload : {}
        this.applyDeptList = obj.content
      })
    },
    // checkbox 点击出发
    handleSelectionChange (list) {
      this.selectList = list
    },
    // 收货地址切换获取联系人和联系电话
    changeAddress (value) {
      let findItem = this.addressList.find(item => {
        return item.value === value
      })
      this.purchaseOrderInfo.userPhone = findItem.userPhone
      this.purchaseOrderInfo.userName = findItem.userName
    },
    // 计算总金额
    orderTotalAmount () {
      let amount = 0
      this.purchaseOrderProductList.forEach(item => {
        if (item.count) {
          amount += item.count * item.buyPrice
        }
      })
      return amount
    },
    // 查询收货地址
    getAddressList () {
      this.addressLoading = true
      this.$axios
        .$post(getAddressListAll, {
          // 断数据来源；1，医院端  2，配送商端'
          yp: 1
        })
        .then(res => {
          const list = isObject(res.payload.content) ? res.payload.content : []
          this.addressList = list.map(item => {
            let obj = {}
            obj = {
              value: item.id,
              label:
                item.province + item.city + item.area + item.detailedAddress,
              userName: item.userName,
              userPhone: item.userPhone
            }
            return obj
          })
        })
        .catch(e => {})
        .finally(() => {
          this.addressLoading = false
        })
    },
    // input 数量切换触发
    resetIllegalInput (scope, value) {
      let id = scope.row.dealerAuthItemId
      this.purchaseOrderProductList.forEach(item => {
        if (item.dealerAuthItemId === id) {
          item.count = Math.round(value)
        }
      })
      this.ProductList()
    },
    // 点击添加产品按钮的回调
    openAddProductDialog () {
      for (let key in this.purchaseOrderInfo) {
        if (!this.purchaseOrderInfo[key]) {
          this.$message({ type: 'warning', message: '请完善基础信息' })
          return
        }
      }
      this.addProductDialogShow = true
    },

    addSelectionToProductList (selection) {
      // 如果选择项中已经添加过了，就按最新的数量更新, 未添加过就格式化一下字段添加
      // todo 如果页面中已经添加了，但在弹窗中又取消了选中怎么处理？
      selection.forEach((item, index) => {
        console.log(index)
        const addedItem = this.purchaseOrderProductList.find(
          addedItem => addedItem.dealerAuthItemId === item.dealerAuthItemId
        )
        item.xUpEnterpriseName = item.upEnterpriseName
        if (addedItem) {
          addedItem.purchaseNum = item.purchaseNum
          this.purchaseOrderProductList.forEach((its, index) => {
            if (addedItem.dealerAuthItemId === its.dealerAuthItemId) {
              // its.count++
            }
          })
        } else {
          item.count = item.purchaseNum
          this.purchaseOrderProductList.push(item)
        }
      })

      this.ProductList()
      this.addProductDialogShow = false
    },

    // 重组数据 计算金额
    ProductList () {
      // 从新组装数据
      let purchaseOrderProductList = cloneDeep(this.purchaseOrderProductList)
      let newArr = []
      purchaseOrderProductList.forEach(item => {
        let obj = this.purList(item.upEnterpriseId)
        newArr.push(obj)
      })
      // 去重
      let uniqByArr = uniqBy(newArr, 'id')

      // 得到最后的数据格式
      let lastArr = []
      uniqByArr.forEach(item => {
        let itemArr = item.arr
        itemArr.forEach(data => {
          lastArr.push(data)
        })
      })
      this.purchaseOrderProductTableList = lastArr
    },

    // 筛选重组合数据
    purList (id) {
      let data = cloneDeep(this.purchaseOrderProductList)
      let arr = []
      // 计算金额
      let num = 0
      let upEnterpriseName = ''
      let upEnterpriseId = ''
      data.forEach(item => {
        if (id === item.upEnterpriseId) {
          num += Number(item.buyPrice || 0) * Number(item.count || 1)
          upEnterpriseName = item.upEnterpriseName
          upEnterpriseId = item.upEnterpriseId
        }
      })
      let numObj = {
        upEnterpriseName: upEnterpriseName,
        upEnterpriseId: upEnterpriseId,
        num: num
      }
      // arr.push(numObj)

      // 查询相同供应商数据重组
      data.forEach(item => {
        if (id === item.upEnterpriseId) {
          arr.push(item)
        }
      })
      let obj = {
        id: id,
        arr: arr
      }

      return obj
    },

    cancelAddSelection () {
      this.addProductDialogShow = false
    },
    // 删除
    deleteOrderProductItem (scope) {
      this.purchaseOrderProductList.forEach((item, index) => {
        if (item.dealerAuthItemId === scope.row.dealerAuthItemId) {
          this.purchaseOrderProductList.splice(index, 1)
        }
      })
      this.ProductList()
    },
    // 提交
    handleSubmit () {
      this.createPurchaseOrder()
    },
    // 提交
    createPurchaseOrder () {
      this.$refs.purchaseOrderForm.validate(valid => {
        if (valid) {
          if (this.purchaseOrderProductList.length === 0) {
            this.$message({ type: 'warning', message: '请添加采购产品' })
            return
          }
          // 将count 赋值给purchaseNum 为了兼容后台规定的参数
          this.purchaseOrderProductList.forEach(item => {
            item.purchaseNum = item.count
          })
          // 根据科室id获取科室名称
          const applyDeptName = this.applyDeptList.filter(item => {
            return item.id === this.purchaseOrderInfo.applyDept
          })[0].departName
          // 根据收货地址id 获取收货地址名称
          const receiveAddressInfo = this.addressList.filter(item => {
            return item.value === this.purchaseOrderInfo.storageAddress
          })[0].label
          const postData = {
            orderType: 1,
            applyDept: applyDeptName,
            receiveAddress: receiveAddressInfo,
            receiveAddressId: this.purchaseOrderInfo.storageAddress,
            contacts: this.purchaseOrderInfo.userName,
            contactNumber: this.purchaseOrderInfo.userPhone,
            productItems: this.purchaseOrderProductList.map(item => {
              console.log(item)
              return {
                authProdId: item.dealerAuthItemId,
                prodCustomCode: item.code,
                platProdCode: item.platProdCode,
                prodName: item.prodName,
                prodSpecs: item.spec,
                prodModel: item.model,
                minUnit: item.unit,
                price: item.buyPrice,
                // registrationId: item.registId,
                registrationNumber: item.registNo,
                manufacturer: item.manufacturer,
                // category: item.bigType,
                prodBigCategory: item.bigType,
                purchaseCount: item.count,
                deliveryCompanyId: item.dealerId,
                deliveryCompanyName: item.dealerName
              }
            })
          }
          this.$axios
            .$post(hospitalwscPurchaseOrderCreate, postData)
            .then(res => {
              if (res.code === '0') {
                this.$message({ type: 'success', message: '新增成功' })
                this.$router.push(
                  '/hospitalSide/orderTracking/wholesaleOrderList'
                )
              }
            })
            .catch(e => {})
        }
      })
    }
  }
}
</script>

<style lang='less'>
.newPurchaseList-box {
  .upEnterpriseNameBox {
    font-size: 16px;
    font-weight: 600;
  }

  .newPurchase-box {
    height: 100%;
    overflow: auto;

    .form-wrapper {
      margin-top: 16px;
      margin-left: -56px;
    }

    .title {
      border-bottom: 1px solid #eee;
      padding-bottom: 10px;
    }

    .top-add-button-wrapper {
      display: flex;
      margin: 24px 0;
      justify-content: space-between;
      .add-button {
        // flex: 1;
      }

      .order-total-amount {
        font-size: 16px;
        font-weight: 500;
      }
    }

    .center-add-button-wrapper {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .edit-form {
      .btnBox {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        // background: pink;
        height: 50px;
      }

      .pagination {
        padding-top: 10px;
        display: flex;
        justify-content: flex-end;
        padding-right: 0;
      }
    }

    .demo-ruleForm {
      // display: flex;
      // width: 500px;

      .el-select {
        width: 100%;
      }
    }

    .ul-list {
      overflow: hidden;
      margin: 10px 0;

      li {
        list-style: none;
        float: left;
        margin-right: 30px;

        i {
          display: inline-block;
          width: 15px;
          height: 10px;
        }

        .auth {
          background: #e6a23c;
        }

        .part {
          background: #eee;
        }
      }
    }
  }
}
</style>
